package com.apotik.legenda.dialog;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellRenderer;

import com.apotik.legenda.custom.TableModelCustom;
import com.apotik.legenda.dao.DoctorDao;
import com.apotik.legenda.model.Doctor;
import com.apotik.legenda.observer.PosObserver;

import javax.swing.JButton;
import javax.swing.JComboBox;

public class AddDokterToTrxDialog extends JDialog implements KeyListener, ActionListener {
	private static final long serialVersionUID = 1L;

	private JTextField textFieldCari;
	private JLabel lblSelectedvalue;
	private TableModelCustom tableModel;
	
	private JButton btnPaginPrev;
	private JButton btnPaginNext;
	private JButton btnSubmit;
	private JButton btnClose;
	
	@SuppressWarnings("rawtypes")
	private DefaultComboBoxModel comboboxModel;
	
	@SuppressWarnings("rawtypes")
	private JComboBox comboBox;
	
	private PosObserver observer;
	private Doctor dokterSelected;
	private int modelRow  = -1;
	private int sizePage = 0;
	
	public AddDokterToTrxDialog(PosObserver observer) {
		this.observer = observer;
		
		setTitle("Add Dokter");
		setSize(500, 300);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		addKeyListener(this);
		//setLocation(190, dim.height-heightFrame-100);
		
		JPanel panelNorth = panelNorth();
		getContentPane().add(panelNorth, BorderLayout.NORTH);
		
		JScrollPane scrollPane = panelCenter();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		
		JPanel panelSouth = panelSouth();
		getContentPane().add(panelSouth, BorderLayout.SOUTH);
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private JPanel panelNorth(){
		JPanel panel = new JPanel();
		panel.setBorder(new EmptyBorder(5, 0, 5, 0));
		panel.setLayout(new BorderLayout());
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.WEST);
		
		JLabel lblCari = new JLabel("Cari:  ");
		lblCari.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_1.add(lblCari);
		
		textFieldCari = new JTextField();
		textFieldCari.addKeyListener(this);
		textFieldCari.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textFieldCari.setHorizontalAlignment(SwingConstants.LEFT);
		textFieldCari.setColumns(14);
		panel_1.add(textFieldCari);
		
		JPanel panel_2 = new JPanel();
		panel.add(panel_2, BorderLayout.EAST);
		
		btnPaginPrev = new JButton("<");
		btnPaginPrev.addActionListener(this);
		panel_2.add(btnPaginPrev);
				
		comboboxModel = new DefaultComboBoxModel(paginationContent());
		
		comboBox = new JComboBox();
		comboBox.setModel(comboboxModel);
		comboBox.addActionListener(this);
		panel_2.add(comboBox);
		
		btnPaginNext = new JButton(">");
		btnPaginNext.addActionListener(this);
		panel_2.add(btnPaginNext);
		
		return panel;
	}
	
	private JScrollPane panelCenter(){
		JScrollPane scrollPane = new JScrollPane();
		
		String[] columnNames = {"No.", "Kode Dokter", "Nama Dokter", "Handphone"};
		tableModel = new TableModelCustom(columnNames);
		loadData(0);
		
		@SuppressWarnings("serial")
		final JTable table = new JTable(){
			@Override
			public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
				JLabel label = (JLabel) super.prepareRenderer(renderer, row, column);
				
				if(column==0){
					label.setHorizontalAlignment(JLabel.CENTER);
				}
				
				return label;
			}
		};
		table.setModel(tableModel);
		table.setEnabled(true);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@SuppressWarnings("rawtypes")
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				int viewRow = table.getSelectedRow();
				if(viewRow>-1){
					modelRow = table.convertRowIndexToModel(viewRow);
					
					Vector v = (Vector) tableModel.getRowVector().get(modelRow);
					if(v!=null){
						dokterSelected = (Doctor) v.get(v.size()-1);
						lblSelectedvalue.setText(dokterSelected.getDoctorCode()+" - "+dokterSelected.getFullName());
					}
					
				}
			}
		});
		scrollPane.setViewportView(table);
		
		return scrollPane;
	}
	
	private JPanel panelSouth(){
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(null);
		
		JLabel lblSelected = new JLabel("Selected");
		lblSelected.setBounds(5, 2, 80, 23);
		lblSelected.setHorizontalAlignment(SwingConstants.LEFT);
		lblSelected.setFont(new Font("Tahoma", Font.PLAIN, 14));
		panel_1.add(lblSelected);
		
		JLabel labelTd1 = new JLabel(":");
		labelTd1.setBounds(67, 2, 21, 23);
		labelTd1.setHorizontalAlignment(SwingConstants.RIGHT);
		labelTd1.setFont(new Font("Tahoma", Font.PLAIN, 14));
		panel_1.add(labelTd1);
		
		lblSelectedvalue = new JLabel("-");
		lblSelectedvalue.setBounds(98, 2, 300, 20);
		lblSelectedvalue.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_1.add(lblSelectedvalue);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new EmptyBorder(3, 0, 3, 9));
		panel.add(panel_2, BorderLayout.EAST);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		btnSubmit = new JButton("Submit");
		btnSubmit.addActionListener(this);
		btnSubmit.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_2.add(btnSubmit, BorderLayout.WEST);
		
		JLabel lblSpaceBtn = new JLabel(" ");
		panel_2.add(lblSpaceBtn, BorderLayout.CENTER);
		
		btnClose = new JButton("Close");
		btnClose.addActionListener(this);
		btnClose.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_2.add(btnClose, BorderLayout.EAST);
		
		
		return panel;
	}
	
	private String[] paginationContent(){
		DoctorDao dao = new DoctorDao();
		
		int sizeRow = dao.size(true, true);
		int divide = sizeRow/10;
		int mod = sizeRow % 10;
		sizePage = divide;
		if(mod!=0){
			sizePage = divide + 1;
		}
		
		String[] result = new String[sizePage];
		for(int i=0;i<sizePage;i++){
			result[i] = Integer.toString(i+1);
		}
		
		return result;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void loadData(int start){
		tableModel.removeRowAll();
		
		DoctorDao dao = new DoctorDao();
		
		List<Doctor> list = dao.listByActiveLimit(true, start, 10);
		if(list.size()>0){
			int i = start+1;
			for(Doctor d : list){
				Vector v = new Vector();
				v.add(i);
				v.add(d.getDoctorCode());
				v.add(d.getFullName());
				v.add(d.getPhoneNumber()!=null ? d.getPhoneNumber():"");
				v.add(d);
				tableModel.insertData(v);
				i++;
			}
		}
	}
	

	@Override
	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();
		if(obj==btnPaginPrev){
			int activePageInt = comboBox.getSelectedIndex();
			if(activePageInt!=0){
				int minusOne = activePageInt-1;
				comboBox.setSelectedIndex(minusOne);
				
				int start = 0;
				String[] paginContent = paginationContent();
				for(int i=0;i<paginContent.length;i++){
					if(i==minusOne){
						start = i*10;
					}
				}
				
				loadData(start);
				
			}
		}else if(obj==btnPaginNext){
			int activePageInt = comboBox.getSelectedIndex();
			int plusOne = activePageInt+1;
			if((plusOne)!=sizePage){
				comboBox.setSelectedIndex(plusOne);
				
				int start = 0;
				String[] paginContent = paginationContent();
				for(int i=0;i<paginContent.length;i++){
					if(i==plusOne){
						start = i*10;
					}
				}
				
				loadData(start);
			}
		}else if(obj==comboBox){
			int activePageInt = comboBox.getSelectedIndex();
			int start = activePageInt * 10;
			loadData(start);
		}else if(obj==btnClose){
			this.setVisible(false);
		}else if(obj==btnSubmit){
			/*if(dokterSelected==null){
				//JOptionPane.showMessageDialog(null, "Tidak ada item yang dipilih", "Exception", JOptionPane.ERROR_MESSAGE);
			}else{
				HashMap<String, Object> hm = new HashMap<>();
				hm.put("doctor", dokterSelected);
				observer.insertDokter(hm);
				
				//this.setVisible(false);
			}*/
			
			HashMap<String, Object> hm = new HashMap<>();
			hm.put("doctor", dokterSelected);
			observer.insertDokter(hm);
			this.setVisible(false);
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void keyPressed(KeyEvent ke) {
		if(ke.getKeyCode()==KeyEvent.VK_ESCAPE){
			this.setVisible(false);
		}
		
		Object obj = ke.getSource();
		
		if(obj==textFieldCari){
			if(ke.getKeyCode()==KeyEvent.VK_ENTER){
				String param = textFieldCari.getText();
				if(param.trim().equalsIgnoreCase("")){
					loadData(0);
					dokterSelected = null;
					lblSelectedvalue.setText("");
				}else{
					DoctorDao dao = new DoctorDao();
					List<Doctor> list = dao.search(param);
					tableModel.removeRowAll();
					if(list.size()>0){
						int i = 1;
						for(Doctor d : list){
							Vector v = new Vector();
							v.add(i);
							v.add(d.getDoctorCode());
							v.add(d.getFullName());
							v.add(d.getPhoneNumber()!=null ? d.getPhoneNumber():"");
							v.add(d);
							tableModel.insertData(v);
							i++;
						}
					}else{
						JOptionPane.showMessageDialog(null, param+" not found", "Exception", JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
	}

}
